<?php
	$setx=0;
	$departments = MDepartment::model()->findAll("is_active = TRUE order by id");
	$department_id = Yii::app()->request->getParam("department_id",$department_id);		
	$department_id = $department_id == "" ? $departments[0]->id : $department_id; 	
 if ((isset($_GET["department_id"])) or (isset($_GET["tahun_ajaran_id"]))) 
 	{	
	if ($_GET["tahun_ajaran_id"]>0){
 		$tahun_ajaran_id = Yii::app()->request->getParam("tahun_ajaran_id",$tahun_ajaran_id);		
		$actTahunAjaran = MTahunAjaran::model()->findAll("id='".$tahun_ajaran_id."' order by id");
		$tahun_ajaran_name=$actTahunAjaran[0]["name"];
		$tahun_ajaran_id=$actTahunAjaran[0]["id"];	
		$start_date = $actTahunAjaran[0]["start_date"];
		$end_date = $actTahunAjaran[0]["end_date"];	
		$setx=0;
		}
		else
		{$setx=1;}
	}
	else
		{$setx=1;}
	if 	($setx==1)			
	{  	
		$actTahunAjaran = CMTahunAjaran::getTahunAjaranActive($department_id);	
		$tahun_ajaran_name=$actTahunAjaran["name"];
		$tahun_ajaran_id=$actTahunAjaran["id"];	
		$start_date = $actTahunAjaran["start_date"];
		$end_date = $actTahunAjaran["end_date"];		
 	}

 
/*	$tahun_ajaran_name=$actTahunAjaran["name"];
	$tahun_ajaran_id=$actTahunAjaran["id"];	
 	$tahun_ajaran_id = Yii::app()->request->getParam("tahun_ajaran_id",$tahun_ajaran_id);		
	$tahun_ajaran_name = Yii::app()->request->getParam("tahun_ajaran_name",$tahun_ajaran_name);				
 */

?>

<script>
	//var departments = <?php //echo $departments?>;
	var department_id = "<?php echo $department_id ?>";	
	function reloadPage(){
		/*		
		$("#tblData").jqGrid("setGridParam",{postData:{"department_id" :$("#department_id").val()},datatype:"json"}).trigger("reloadGrid");		
		$("#tblData").jqGrid("setGridParam",{page:8}).trigger("reloadGrid");		
		$("#idSrcTblData").val("");
		*/
		//refreshGrid();
		window.location.replace("index.php?r=akademik/kalender_akademik/main&department_id=" + $("#department_id").val()+ "&tahun_ajaran_id=" + $("#tahun_ajaran_id").val());
	}

	function refreshGrid(){		
		$("#tblData").jqGrid("setGridParam",{
			postData:{
				"department_id" :$("#department_id").val(),
				"tahun_ajaran_id" :$("#tahun_ajaran_id").val(),
			},
			datatype:"json"
		}).trigger("reloadGrid");
		$("#idSrcTblData").val("");
	}
	
	function newData(){
	
		var url="index.php?r=akademik/kalender_akademik/main/form&op=add&department_id=" + $("#department_id").val()+ "&tahun_ajaran_id=" + $("#tahun_ajaran_id").val();
		var winName = "formTahunAjaran";
		var specs ="menubar=0,scrollbars=1,status=0,titlebar=0,toolbar=0";
		var width=450,height=300;
		var replace = false,onCenter = true;
		w = openWindow(winName,url,width,height,onCenter,specs,replace);
		w.focus();
		var timer = setInterval(function() {   
			if(w.closed) {  
				clearInterval(timer);  
				reloadPage();
			}  
		}, 1000);
	}
	
	function popupRow(filter_name,idmonth,idyear){		
		var url="index.php?r=akademik/kalender_akademik/main/popupWindow&filter_name="+filter_name+"&idmonth="+idmonth+"&idyear="+idyear+"&department_id=" + $("#department_id").val()+ "&tahun_ajaran_id=" + $("#tahun_ajaran_id").val();
		var winName = "DetailIndex";
		var specs ="menubar=0,scrollbars=1,status=0,titlebar=0,toolbar=0";
		var width=450,height=300;
		var replace = true,onCenter = true;
		w = openWindow(winName,url,width,height,onCenter,specs,replace);
		w.focus();		
		var timer = setInterval(function() {   
			if(w.closed) {  
				clearInterval(timer);  
				reloadPage();
			}  
		}, 1000);
	}	
	/*
	function printData(){
		var url="index.php?r=akMaster_TahunAjaran/print&department_id=" + $("#department_id").val();
		var winName = "Master Tahun Ajaran";
		var specs ="menubar=0,scrollbars=1,status=0,titlebar=0,toolbar=0";
		var width=450,height=300;
		var replace = false,onCenter = true;
		w = openWindow(winName,url,width,height,onCenter,specs,replace);
	}
	*/
	
	function closeTest(){
		
	}
	/*
	function editRow(id){		
		var url="index.php?r=akPMB/form&op=edit&id=" + id;
		var winName = "";
		var specs ="menubar=0,scrollbars=1,status=0,titlebar=0,toolbar=0";
		var width=1000,height=800;
		var replace = true,onCenter = true;
		w = openWindow(winName,url,width,height,onCenter,specs,replace);
		var timer = setInterval(function() {   
			if(w.closed) {  
				clearInterval(timer);  
				reloadPage();
			}  
		}, 1000);
	}
	
	function deleteRow(id){
		if (confirm("Delete data ?")){			
			window.parent.showLoader();			
			var data = $("#tblData").jqGrid("getRowData",id);
			var editUrl = $("#tblData").jqGrid("getGridParam","editUrl");			
			$.ajax({	
				url : editUrl,
				type:"GET",
				async:true,
				data: {op: "del",id:data.id},
				success: function(data) {
					if(data.actionStatus == 0){
						//sukses
						$("#tblData").jqGrid("setCell",id,"is_active","false");	
					}else if(data.actionStatus == 1){
						alert(data.actionMessage);
					}						
				},
				complete:function(){
					window.parent.hideLoader();
				}
			});
			//$("#tblData").jqGrid("delRowData",id);
		}
	}
	*/
	function getTahunAjaran(obj){
		oldValue = $("#tahun_ajaran_id").val();
		if (obj ===""){
			$("#tahun_ajaran_id").val("");
			$("#tahun_ajaran_name").val("");
		}else{
			$("#tahun_ajaran_id").val(obj.id);
			$("#tahun_ajaran_name").val(obj.name);
				var	department_id=$("#department_id").val();
				var	tahun_ajaran_name=$("#tahun_ajaran_name").val();		
				var	tahun_ajaran_id=$("#tahun_ajaran_id").val();				
				window.location.replace("index.php?r=akademik/kalender_akademik/main&tahun_ajaran_name="+tahun_ajaran_name+"&tahun_ajaran_id="+tahun_ajaran_id+"&department_id="+department_id);			
		}
		if (oldValue != $("#tahun_ajaran_id").val()){
			//refreshGrid();
		}
		
	}
 
	/*
	$(function(){
		var numberTemplate = {formatter: 'number', align: 'right', sorttype: 'number'};	 
		$("#tblData").jqGrid({
			url:'index.php?r=akPMB/pMBSummaryList',
			editUrl:'index.php?r=akPMB/edit',
			postData:{"department_id":1},
			datatype: 'local',
			loadonce:true,
			mtype:"GET",
			autowidth:true,
			height:"100%",
			altRows:true,
			ignoreCase:true,
			//$strFields="id,department_id,sid,name,if(gender='P','Pria','Wanita') as gender,birth_date,address,home_phone,handphone,email,ayah_nama,ibu_nama,wali_nama,is_active";
			colNames: ['id','SID','Tahun Ajaran', 'Nama',  'Jenis Kelamin', 'Tgl Lahir', 'Alamat','No Telp','Handphone','Alamat email','Ayah','Ibu','Wali','Status','Action'],
			colModel: [
				{name: 'id', index: 'id', width: 20,hidden:false,sorttype:'int',formatter:'int'},
				{name: 'sid', index: 'sid', width: 40,search:true},
				{name: 'tahun_ajaran', index: 'tahun_ajaran', width: 50,search:false,align:"center"},
				{name: 'name', index: 'name', width: 100,search:true},
				{name: 'gender', index: 'gender', width: 50,search:true},
				{name: 'birth_date', index: 'birth_date', width: 60, align: 'left', sorttype: 'date',
					formatter: 'date', formatoptions: {newformat: 'd-M-Y'}, datefmt: 'd-M-Y'},
				{name: 'address', index: 'address',width: 200},
				{name: 'home_phone', index: 'home_phone',width: 50},
				{name: 'handphone', index: 'handphone',width: 50},
				{name: 'email', index: 'email',width: 50},
				{name: 'ayah_nama', index: 'ayah_nama',width: 100,hidden:true},
				{name: 'ibu_nama', index: 'ibu_nama',width: 100,hidden:true},
				{name: 'wali_nama', index: 'wali_nama',width: 100,hidden:true},				
				{name: 'is_active', index: 'is_active', width: 30, align: 'center', formatter: 'checkbox'},
				{name: 'act', index: 'act', width: 40, align: 'center'},
				
			],
			gridview: true,
			rownumbers: false,
			rowNum: 10,
			rowList: [5, 10, 15],
			pager: '#navTblData',
			viewrecords: true,
			caption: 'Daftar Murid',
			jsonReader : { 
				root:"model",
				repeatitems: false			
			},
			loadComplete:function(data){
				console.log(data);
			},
			gridComplete: function(){ 
				var ids = jQuery("#tblData").getDataIDs(); 
				for(var i=0;i<ids.length;i++){ 
					var cl = ids[i]; 
					//btnEdit = "<input style='height:22px;width:20px;' type='button' value='E' onclick=jQuery('#rowed2').editRow("+cl+"); ></ids>"; 
					//btnDelete = "<input style='height:20px;width:20px;' type='button' value='S' onclick=jQuery('#rowed2').saveRow("+cl+"); />"; 
					btnEdit = "<img title='edit' class='imgBtn' style='height:20px;width:20px;' src='images/action/Actions-Edit-icon.png' onclick='editRow(" + cl + ")' />"; 
					btnDelete = "<img title='delete' class='imgBtn' style='margin-left:5px;height:20px;width:20px;' src='images/action/Actions-Delete-icon.png' onclick='deleteRow(" + cl + ")' />"; 
					jQuery("#tblData").setRowData(ids[i],{act:btnEdit+btnDelete}) 
				} 
			}
		});
		$("#tblData").jqGrid('navGrid','#navTblData',{add:false,edit:false,search:false,del:false,refresh:false});
		
		//add search text
		$("#tblData").jqGrid('addSearchText',["sid","name","address"]);
	});
	*/
</script>
<style>
table.jadwal, td, tr
{
border:1px solid grey;  
text-align:center; 
}
td.picked {background:#33FFFF;} 
td.picked_off {background:#ccc;} 
/*
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
*/
</style>
<div style="">
	<script>
		$(function(){
			$("#tblData").jqGrid("setGridParam",{postData:{"department_id" :$("#department_id").val()},datatype:"json"}).trigger("reloadGrid");			
			$("#department_id").change(function(){
				var	department_id=$("#department_id").val();
				var	tahun_ajaran_name=$("#tahun_ajaran_name").val();		
				var	tahun_ajaran_id=0;				
				window.location.replace("index.php?r=akademik/kalender_akademik/main&tahun_ajaran_name="+tahun_ajaran_name+"&tahun_ajaran_id="+tahun_ajaran_id+"&department_id="+department_id);			
			});
		});	
	</script>
<form method="post" id="frmFilter" name="frmFilter">
		<div>
			<?php
				//$dep = Yii::app()->request->getParam("department","0");
				$rsDep = MDepartment::model()->findAll(array("condition"=>"is_active = TRUE","order"=>"id"));
				$arrOptions=array();
				foreach($rsDep as $rw){
					$selected = $department_id == $rw->id ? true : false;
					$arrOptions[] = array("label"=>$rw->name,"value"=>$rw->id,"selected"=>$selected);
				}
				
				$this->widget('application.components.widgets.SelectField', 
					array("name"=>"department_id",
						"value"=>"",
						"htmlOptions"=>"",
						"label"=>array(
							"value"=>"Department",
							"htmlOptions"=>"class ='mandatory' style='display:inline-block;width:100px'"
						),
						"options"=>$arrOptions,
					)
				);
				
			?>		
		</div>
        </form>
		<div>
			<label class="form" style="width:100px"><?php echo Yii::t("label","Tahun Ajaran");?></label>
			<input type="hidden" id="tahun_ajaran_id" name="tahun_ajaran_id" value="<?php echo $tahun_ajaran_id; ?>" size="2" />
            
			
			<?php
				$this->widget('application.components.widgets.FindTextField',
					array('options' => array('id'=>'tahun_ajaran_name','value'=>$tahun_ajaran_name,'disabled'=>''),
							'windowParams' => array('url'=>"index.php?r=data_popup/tahunAjaran" ,
								'specs'=> array('height'=>300,'width'=>800),
								'name'=> "popTahunAjaran",
							),
							'callback'=>"getTahunAjaran",
							'beforePopupFunc'=>"",
					)
				);
			?>
			
					
		</div>
 
	<div style="float:rigth">
	<?php 
		$this->widget('application.components.widgets.ActionBar', 
			array("menuAlign" => "right", 
				'items' => array(
					array(
						'id' => "btnRefresh",
						'title' => Yii::t("menu","Segarkan"),
						'icon' => "images/action/Action-Refresh-icon.png",
						'callback'=>"reloadPage"
					),					
					array(
						'id' => "btnNew",
						'title' => Yii::t("menu","Baru"),
						'icon' => "images/action/Actions-document-new-icon.png",
						'callback'=>"newData"
					),
					array(
						'id' => "btnNew",
						'title' => Yii::t("menu","Cetak"),
						'icon' => "images/action/Actions-document-print-icon2.png",
						'callback'=>"printData"
					),					
					
				)
			)
		);
	?>
    <?php
 	echo '<table border=1>';
	echo '<tr><td colspan=2>Information</td>';
	for ($xdata=1; $xdata<=31; $xdata++)
	{
		echo '<td>'.$xdata.'</td>';
	}
	echo '</tr>';
 if (isset($start_date))		 
	{
	//echo $tahun_ajaran_name;
		while (strtotime($start_date) <= strtotime($end_date)) 
		{
			$m =  date_create($start_date)->format('m');
			$y =  date_create($start_date)->format('Y');		
			$y2=$y+1;

			$mcon= Yii::app()->db;
			$sql1='select name,detail_activity, start_date, end_date,day(start_date) as start_day,month(start_date) as start_month,year(start_date) as start_year,day(end_date) as end_day,month(end_date) as end_month,year(end_date) as end_year from m_kalender_akademik where   department_id="'.$department_id.'" and tahun_ajaran_id='.$tahun_ajaran_id.' and ((( '.$m.' between month(start_date) and month(end_date))   and year (start_date)='.$y.'  ) or ((month(start_date)='.$m.') and year(end_date)='.$y2.'  ) or ((month(end_date)='.$m.') and year(end_date)='.$y.' ))    group by name ORDER BY  start_date,name';
			$mKalenderAkademik=$mcon->createCommand($sql1);		
			$rsDep=$mKalenderAkademik->queryAll();	
			$countrw=0;
			$json = CJSON::encode($rsDep);
			$arr_kalender = json_decode($json,true);
			$countrw=count($arr_kalender);
			if ($countrw>0)
			{
//			echo    date("F", mktime(0, 0, 0, $m, 1)).' '.$y.' - ';
//			echo $countrw.'<br>';			
			echo '<tr><td rowspan='.$countrw.'>'.  date("F", mktime(0, 0, 0, $m, 1)).' '.$y.'</td> ';								
				for ($xdata=0; $xdata<count($arr_kalender); $xdata++)
				{
					$activity = $arr_kalender[$xdata]['name'];
					echo '<td><a href="#" onclick="javascript:popupRow(\''.$activity.'\','.$m.','.$y.');">'.$activity.'</a></td>';
					$stmonth=intval($m);
					$numDays = cal_days_in_month (CAL_GREGORIAN, $m,$y);		
				
					$sql1d='select name,detail_activity, start_date, end_date,day(start_date) as start_day,month(start_date) as start_month,year(start_date) as start_year,day(end_date) as end_day,month(end_date) as end_month,year(end_date) as end_year from m_kalender_akademik where name="'. $arr_kalender[$xdata]['name'].'" and department_id="'.$department_id.'" and tahun_ajaran_id='.$tahun_ajaran_id.' and ((( '.$m.' between month(start_date) and month(end_date))   and year (start_date)='.$y.'  ) or ((month(start_date)='.$m.') and year(end_date)='.$y2.'  ) or ((month(end_date)='.$m.') and year(end_date)='.$y.' ))    ORDER BY name, start_date';
					$mKalenderAkademikd=$mcon->createCommand($sql1d);		
					$rsDepd=$mKalenderAkademikd->queryAll();	
					$countrw=0; 
					$jsond = CJSON::encode($rsDepd);
					$arr_kalender_akademik = json_decode($jsond,true);
					$countrd=count($arr_kalender_akademik);			
					if ($countrd>0)
					{
						for ($xday=1; $xday<32; $xday++)
						{
						$e=0;
							for ($xdatar=0; $xdatar<count($arr_kalender_akademik); $xdatar++)
							{
							//echo count($arr_kalender_akademik).'-';
							$startmonth=$arr_kalender_akademik[$xdatar]['start_month'];
							$endmonth=$arr_kalender_akademik[$xdatar]['end_month'];
							$startday=$arr_kalender_akademik[$xdatar]['start_day'];
							$endday=$arr_kalender_akademik[$xdatar]['end_day'];							
//							echo  $arr_kalender_akademik[$xdatar]['detail_activity'] . '';
								if ($xday>$numDays){ } else
								{
									if ( 
										((($stmonth==$startmonth) and ($stmonth!=$endmonth)) and ($xday>=$startday))
										or
										((($stmonth!=$startmonth) and ($stmonth==$endmonth)) and ($xday<=$endday))
										or 
										(($stmonth>$startmonth) and ($stmonth<$endmonth))		
										or 	 
										((($stmonth==$startmonth) and ($stmonth==$endmonth)) and (($xday>=$startday) and ($xday<=$endday)))					
										)
										{	
											$e=1;
										} 
									else
										{	if ($e==1){$e=1;} else {$e=0;}	}  
								}
							}			
							if ($xday>$numDays){echo '<td class="picked_off"></td>';} else
								{		
									if ($e==0){echo '<td>'.$xday.'</td>';}	else {echo '<td class="picked">'.$xday.'</td>';	}
								}
						}						
					}
					echo '</tr>';
				}
			}

/*		
			$mcon= Yii::app()->db;
			$sql1='select name,detail_activity, start_date, end_date,day(start_date) as start_day,month(start_date) as start_month,year(start_date) as start_year,day(end_date) as end_day,month(end_date) as end_month,year(end_date) as end_year from m_kalender_akademik where   department_id="'.$department_id.'" and tahun_ajaran_id='.$tahun_ajaran_id.' and ((( '.$m.' between month(start_date) and month(end_date))   and year (start_date)='.$y.'  ) or ((month(start_date)='.$m.') and year(end_date)='.$y2.'  ) or ((month(end_date)='.$m.') and year(end_date)='.$y.' ))     ORDER BY name, start_date';
			$mKalenderAkademik=$mcon->createCommand($sql1);		
			$rsDep=$mKalenderAkademik->queryAll();	
			$countrw=0;
			$json = CJSON::encode($rsDep);
			$arr_kalender = json_decode($json,true);
			$countrw=count($arr_kalender);
			if ($countrw>0)
			{
		//	echo '<tr><td colspan=35>'.$sql1.'</td></tr>';
				echo '<tr><td rowspan='.$countrw.'><a href="#" onclick="javascript:popupRow('.$m.','.$y.');">'.  date("F", mktime(0, 0, 0, $m, 1)).' '.$y.'</a></td> ';	
				for ($xdata=0; $xdata<count($arr_kalender); $xdata++)
				{
					$activity = $arr_kalender[$xdata]['detail_activity'];
					$startmonth=$arr_kalender[$xdata]['start_month'];
					$endmonth=$arr_kalender[$xdata]['end_month'];
					$startday=$arr_kalender[$xdata]['start_day'];
					$endday=$arr_kalender[$xdata]['end_day'];
					$stmonth=intval($m);
					$numDays = cal_days_in_month (CAL_GREGORIAN, $m,$y);		
					echo '<td>'.$activity.'</td>';
					
					for ($xday=1; $xday<32; $xday++)
					{
					//$time = mktime(0, 0, 0, $m, $xday, $y);
					//$weekday = date('w', $time);
						if ($xday>$numDays){echo '<td class="picked_off"></td>';} else
						{
							if ( 
								((($stmonth==$startmonth) and ($stmonth!=$endmonth)) and ($xday>=$startday))
								or
								((($stmonth!=$startmonth) and ($stmonth==$endmonth)) and ($xday<=$endday))
								or 
								(($stmonth>$startmonth) and ($stmonth<$endmonth))		
								or 	 
								((($stmonth==$startmonth) and ($stmonth==$endmonth)) and (($xday>=$startday) and ($xday<=$endday)))					
								)
								{	echo '<td class="picked"></td>';	
								}
							else
								{	echo '<td></td>';	}
						}
					}		 
					echo '</tr>';		
				}		
			}
					echo '</tr>';	
				
			//	echo "$start_date - ";
		 
		 
		//		 echo $numDays.'<br>';
		*/
				$start_date = date ("Y-m-d", strtotime("+1 month", strtotime($start_date)));
		 
		}
	}
	  
	?>
	</div>	
 
</div>